import Taro from '@tarojs/taro';
import { decrypt as commonDecypt } from './secret';
var formData;
//文件保存路径
var folderPath;
export var folderPathEvent = function (cb) {
    folderPath = cb;
};
//解密方法
var decrypt;
export var decryptEvent = function (cb) {
    decrypt = cb;
};
// 生成文件名
var generateKey = function (filePath) {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var path = year + (month < 10 ? '0' + month : month).toString();
    var fileKey = (folderPath ? folderPath(filePath) : 'default/') +
        path +
        '/' +
        new Date().getTime() +
        filePath.substring(filePath.lastIndexOf('.'));
    return fileKey;
};
var executeUpload = function (filePath, _a, privateOss, ossConfig) {
    var _b = _a === void 0 ? {} : _a, host = _b.host, policy = _b.policy, signature = _b.signature, accessId = _b.accessId;
    if (privateOss === void 0) { privateOss = false; }
    var key = generateKey(filePath);
    var formData = {
        key: key,
        OSSAccessKeyId: accessId,
        policy: policy,
        signature: decrypt ? decrypt(signature) : commonDecypt(signature),
        success_action_status: '200'
    };
    return new Promise(function (resolve, reject) {
        Taro.uploadFile({
            url: host,
            formData: formData,
            filePath: filePath,
            name: 'file',
            success: function () {
                var wholePath = privateOss
                    ? ossConfig.cdnS + key
                    : ossConfig.cdn + key;
                resolve(wholePath);
            },
            fail: reject
        });
    });
};
var signatureVerification = function () {
    if (!formData) {
        return null;
    }
    var expireAt = formData.expireAt;
    // 已经快过期了
    if (expireAt - Date.now() < 30 * 1000) {
        return null;
    }
    return formData;
};
/**
 * @param filePath 小程序的模板路径
 * @param everytimeSignature 是否每次都重新获取签名，默认为true
 * @param privateOss 是否是私有域上传，默认为false
 */
export var uploadToOss = function (filePath, securitySignApi, apiData, ossConfig, everytimeSignature, privateOss) {
    if (apiData === void 0) { apiData = {}; }
    if (everytimeSignature === void 0) { everytimeSignature = true; }
    if (privateOss === void 0) { privateOss = false; }
    if (!everytimeSignature) {
        if (signatureVerification()) {
            return executeUpload(filePath, signatureVerification(), privateOss, ossConfig);
        }
    }
    return securitySignApi(apiData).then(function (res) {
        formData = res;
        return executeUpload(filePath, res, privateOss, ossConfig);
    });
};
